package com.docker.sys.dept;

import com.docker.core.mvc.service.BaseService;
import com.jfinal.aop.Inject;
import com.jfinal.kit.Okv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;
import kit.docker.convert.RecordKit;

import java.util.List;

/**
 * @Author ldl
 * @Create 2020/11/24 024 15:34
 */
public class DeptService extends BaseService {

    @Inject
    private DeptDao deptDao;

    public List<Record> list(Okv cond) {
        return deptDao.list(cond);
    }

    public boolean save(DeptBean bean) {
        if (deptDao.exist(bean.getDept_code(), "-1")) {
            throwError("部门编码已存在");
        }
        bean.setDept_id(getUUID32());
        bean.setDept_code(creatCode(bean.getDept_pcode()));
        if (StrKit.isBlank(bean.getDept_pcode())) {
            bean.setDept_pcode("0");
        }
        bean.setStatus_flag("1");
        if (!deptDao.save(RecordKit.objectToRecord(bean))) {
            throwError("部门信息保存失败");
        }
        return true;
    }

    private String creatCode(String deptPCode) {
        String maxDeptCode = deptDao.maxDeptCode(Okv.by("dept_pcode", deptPCode));
        if (StrKit.isBlank(maxDeptCode)) {
            if (StrKit.isBlank(deptPCode)) {
                return "10";
            }
            return deptPCode + "01";
        }
        return String.valueOf(Integer.valueOf(maxDeptCode) + 1);
    }

    public boolean update(DeptBean bean) {
        Record dept = info(bean.getDept_id());
        dept.set("dept_name", bean.getDept_name());
        if (!deptDao.update(dept)) {
            throwError("部门信息保存失败");
        }
        return true;
    }

    public Record info(String deptId) {
        Record dept = deptDao.info(deptId);
        if (!StrKit.notNull(dept)) {
            throwError("部门不存在");
        }
        return dept;
    }

}
